package com.oneday.nuo.base.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.oneday.nuo.base.config.BaseService;
import com.oneday.nuo.base.dao.NuoRoleAuthDAO;
import com.oneday.nuo.base.dao.NuoRoleAuthViewDAO;
import com.oneday.nuo.base.dto.NuoRoleAuthViewDTO;
import com.oneday.nuo.base.entity.NuoRoleAuthEntity;

import com.oneday.nuo.base.entity.NuoRoleAuthViewEntity;
import com.oneday.nuo.base.entity.NuoRoleEntity;
import com.oneday.nuo.base.exception.NuoException;
import com.oneday.nuo.base.service.NuoRoleAuthViewService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * (NuoRoleAuthView)表服务实现类
 *
 * @author liushuai
 * @since 2021-04-23 18:13:39
 */
@Service("nuoRoleAuthViewService")
public class NuoRoleAuthViewServiceImpl extends BaseService<NuoRoleAuthViewDAO, NuoRoleAuthViewEntity> implements NuoRoleAuthViewService {

    @Autowired
    private NuoRoleAuthViewDAO nuoRoleAuthViewDao;


    @Override
    public void saveRoleAuthView(List<String> auths, String roleId) {
        if(StrUtil.isEmpty(roleId)){
            throw new NuoException("角色id不能为空");
        }
        LambdaQueryWrapper<NuoRoleAuthViewEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(NuoRoleAuthViewEntity::getRoleId,roleId);
        nuoRoleAuthViewDao.delete(wrapper);
        if(CollectionUtils.isNotEmpty(auths)){
            List<NuoRoleAuthViewEntity> entities = new ArrayList<>();
            auths.forEach(res->{
                entities.add(NuoRoleAuthViewEntity.builder()
                        .authId(res)
                        .roleId(roleId)
                        .build());
           });

            this.saveBatch(entities);
        }

    }

    @Override
    public List<String> queryAuthIdsByRoleId(String roleId) {
        LambdaQueryWrapper<NuoRoleAuthViewEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(NuoRoleAuthViewEntity::getAuthId);
        wrapper.eq(NuoRoleAuthViewEntity::getRoleId,roleId);
        List<NuoRoleAuthViewEntity> nuoRoleAuthEntities = nuoRoleAuthViewDao.selectList(wrapper);
        List<String> ids = nuoRoleAuthEntities.stream().map(NuoRoleAuthViewEntity::getAuthId).collect(Collectors.toList());
        return ids;
    }
}
